<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="收款状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择收款状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_IN_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款日期" prop="receiveDateStr">
        <el-date-picker
          v-model="queryParams.receiveDateStr"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
<!--      <el-form-item label="是否生效" prop="isValid">-->
<!--        <el-input-->
<!--          v-model="queryParams.isValid"-->
<!--          placeholder="请输入是否生效"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="开票状态" prop="taxStatus">
        <el-select
          v-model="queryParams.taxStatus"
          placeholder="请选择开票状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_TAX_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同类型" prop="contractArchiveInfo.contractType">
        <el-select  v-model="queryParams.contractArchiveInfo.contractType"  placeholder="请选择合同类型"
                    clearable
                    class="!w-240px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_CONTRACT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同名称/合同编号" prop="contractArchiveInfo.contractName" label-width="140">
        <el-input
          v-model="queryParams.contractArchiveInfo.contractName"
          placeholder="请输入合同名称/合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          @click="openForm('create')"-->
<!--          v-hasPermi="['biz:contract-archive-receive-record:create']"-->
<!--        >-->
<!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
<!--        </el-button>-->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['biz:contract-archive-receive-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            :disabled="isEmpty(checkedIds)"-->
<!--            @click="handleDeleteBatch"-->
<!--            v-hasPermi="['biz:contract-archive-receive-record:delete']"-->
<!--        >-->
<!--          <Icon icon="ep:delete" class="mr-5px" /> 批量删除-->
<!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
        :preserve-expanded-content="preserveExpanded"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column type="expand">
        <template #default="props">
          <div style="width: 60%;margin-left: 120px">
            <el-table :data="props.row.payment" :border="childBorder" :show-overflow-tooltip="true">
              <el-table-column label="应收款日期" prop="effectDate"  align="center" :formatter="dateFormatter2"
                               width="120px"/>
              <el-table-column label="实际收款日期" prop="payDateImp"         :formatter="dateFormatter2"
                               width="120px" />
              <el-table-column label="客户名称" prop="customerName" />
              <el-table-column label="收款内容" prop="content" />
              <el-table-column label="应收金额" prop="totalMoney" />
              <el-table-column label="已收金额" prop="payMoney" />
<!--              <el-table-column label="本次匹配金额" prop="thisMacthMoney" />-->
<!--              <el-table-column label="剩余金额" align="center" prop="totalMoney" >-->
<!--                <template #default="scope">-->
<!--                  {{parseInt(scope.row.totalMoney ? scope.row.totalMoney:0) - parseInt(scope.row.payMoney ?scope.row.payMoney:0)}}-->
<!--                </template>-->
<!--              </el-table-column>-->
              <el-table-column label="未收金额" align="center" prop="totalMoney"  >
                <template #default="scope">
                  {{parseInt(scope.row.totalMoney ? scope.row.totalMoney:0) - parseInt(sumPayments(props.row.payment) ?sumPayments(props.row.payment):0)}}
                </template>
              </el-table-column>
              <el-table-column label="经手人" prop="recorderName" />
              <el-table-column label="备注" prop="remarks" />
<!--              <el-table-column label="操作" fixed="right" align="center">-->
<!--                <template #default="scope">-->
<!--                    <el-button-->
<!--                      link-->
<!--                      type="danger"-->
<!--                      @click="handleDelete(scope.row.id)"-->
<!--                      v-hasPermi="['biz:contract-archive-receive-record:delete']"-->
<!--                    >-->
<!--                      删除-->
<!--                    </el-button>-->
<!--                </template>-->
<!--              </el-table-column>-->
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="收款状态" align="center" width="90" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BIZ_CONTRACT_IN_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="contractArchiveInfo.customerName" width="120" />
      <el-table-column label="合同编号" align="center" prop="contractArchiveInfo.contractCode"  width="120"/>
      <el-table-column label="合同名称" align="center" prop="contractArchiveInfo.contractName"  width="120"/>
      <el-table-column label="期数" align="center" prop="instalmentCount" />
<!--      <el-table-column-->
<!--        label="收款日期"-->
<!--        align="center"-->
<!--        prop="receiveDate"-->
<!--        :formatter="dateFormatter"-->
<!--        width="180px"-->
<!--      />-->
<!--      <el-table-column label="应收金额" align="center" prop="alreadyReceiveMoney" />-->
      <el-table-column label="应收金额" align="center" prop="receiveMoney"/>
      <el-table-column label="已收金额" align="center" prop="payMoney" >
        <template #default="scope">
          {{ sumPayments(scope.row.payment) }}
        </template>
      </el-table-column>
<!--      <el-table-column label="已收金额" align="center" prop="alreadyReceiveMoney">-->
<!--        <template #default="scope">-->
<!--          {{scope.row.alreadyReceiveMoney ?scope.row.alreadyReceiveMoney: 0}}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="未收金额" align="center" prop="alreadyReceiveMoney">
        <template #default="scope">
          {{ parseFloat(scope.row.receiveMoney ? scope.row.receiveMoney: 0) - parseFloat(sumPayments(scope.row.payment) ?sumPayments(scope.row.payment): 0)}}
        </template>
      </el-table-column>
<!--      <el-table-column label="收款日期" align="center" prop="receiveDate">-->
<!--        <template #default="scope">-->
<!--          {{ formatTime(scope.row.receiveDate)}}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column
        label="应收日期"
        align="center"
        prop="receiveDate"
        :formatter="dateFormatter2"
        width="120px"
      />
      <el-table-column label="收款内容" width="180" align="center" prop="content" />
      <el-table-column label="收款负责人"  width="110"  align="center" prop="recorderName" />
      <el-table-column label="开票状态"   width="110"  align="center" prop="taxStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BIZ_CONTRACT_TAX_STATUS" :value="scope.row.taxStatus" />
        </template>
      </el-table-column>
      <el-table-column label="服务团队" align="center" prop="contractArchiveInfo.serviceUnitName" width="120" />
      <el-table-column label="任务状态" align="center" prop="status"  width="120" >
        {{'通知客户收款'}}
<!--        <template #default="scope">-->
<!--          <dict-tag :type="DICT_TYPE.BIZ_CONTRACT_IN_STATUS" :value="scope.row.status" />-->
<!--        </template>-->
      </el-table-column>
<!--      <el-table-column label="类型" align="center" prop="receiptCode" />-->
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column
        label="坏账日期"
        align="center"
        prop="badDebtDate"
        :formatter="dateFormatter2"
        width="120px"
      />
      <el-table-column label="坏账原因" align="center" prop="badDebtReason"   width="120px"/>
<!--      <el-table-column label="收款内容" align="center" prop="content" />-->
      <el-table-column label="操作" fixed="right" align="center" min-width="260px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['biz:contract-archive-receive-record:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="openInvoiceFormRefForm(scope.row)"
            v-hasPermi="['biz:contract-archive-receive-record:update']"
          >
            开票
          </el-button>
<!--          /biz/expand/biz-invoice-management-->
          <router-link :to="'/biz/expand/biz-invoice-management?id='+scope.row.contractArchiveInfo.contractCode">
            <el-button link type="primary">发票管理</el-button>
          </router-link>
          <router-link :to="'/biz/expand/biz-payment-management?id='+scope.row.contractArchiveInfo.contractCode">
            <el-button link type="primary">收款管理</el-button>
          </router-link>
<!--          <el-button-->
<!--            link-->
<!--            type="danger"-->
<!--            @click="handleDelete(scope.row.id)"-->
<!--            v-hasPermi="['biz:contract-archive-receive-record:delete']"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ContractArchiveReceiveRecordForm ref="formRef" @success="getList" />
   <el-dialog v-model="dialogFormVisible" title="开票记录" width="1000" destroy-on-close>
    <div style="width:100%;height:500px;overflow-y:auto;overflow-x: hidden">
      <!-- 表单弹窗：添加/修改 -->
      <BizInvoiceManagementForm :rowData="currentRowData"  ref="invoiceFormRef" @success="getList" />
    </div>
    <!--    <template #footer>-->
    <!--      <div class="dialog-footer">-->
    <!--        <el-button @click="dialogFormVisible = false">Cancel</el-button>-->
    <!--        <el-button type="primary" @click="dialogFormVisible = false">-->
    <!--          Confirm-->
    <!--        </el-button>-->
    <!--      </div>-->
    <!--    </template>-->
  </el-dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { ContractArchiveReceiveRecordApi, ContractArchiveReceiveRecord } from '@/api/biz/receivables'
import ContractArchiveReceiveRecordForm from './ContractArchiveReceiveRecordForm.vue'
import BizInvoiceManagementForm from '../invoice/index.vue'
const invoiceFormRef = ref()
const contractCode = ref('')
const dialogFormVisible = ref(false)
/** 应收款管理 列表 */
defineOptions({ name: 'BizContractArchiveReceiveRecord' })
const childBorder = ref(false)
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const preserveExpanded = ref(false)
const loading = ref(true) // 列表的加载中
const list = ref<ContractArchiveReceiveRecord[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: undefined,
  // receiveDate: [],
  isValid: undefined,
  taxStatus: undefined,
  receiveDateStr: [],
  contractArchiveInfo: {
    contractType: undefined,
    contractName: undefined
  }
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const contractReceive = ref({})
const currentRowData = ref({});
// 返回对象数组中付款金额的总和
const sumPayments = (arr) => arr.reduce((sum, item) => sum + (item.payMoney || 0), 0);
const sumPaymentsBq = (arr,qs) => {
  let newArr = arr.filter(a => a.periods == qs);
  return newArr.reduce((sum, item) => sum + (item.payMoney || 0), 0);
}
// import { nextTick } from 'vue'
const openInvoiceFormRefForm = async (row) => {
  // console.info(row)
  if(!row.contractArchiveInfo.contractCode){
    message.error(t('合同编号不存在'))
    return
  }
  currentRowData.value =  JSON.parse(JSON.stringify(row));
  dialogFormVisible.value = true
  // contractReceive.value = row
  // console.info(invoiceFormRef.value)
  invoiceFormRef.value.getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContractArchiveReceiveRecordApi.getContractArchiveReceiveRecordPage(queryParams)
    list.value = data.records
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractArchiveReceiveRecordApi.deleteContractArchiveReceiveRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除应收款管理 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ContractArchiveReceiveRecordApi.deleteContractArchiveReceiveRecordList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ContractArchiveReceiveRecord[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContractArchiveReceiveRecordApi.exportContractArchiveReceiveRecord(queryParams)
    download.excel(data, '应收款管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
